import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:reactive_forms/reactive_forms.dart';
import 'package:yt_devops/components/app_bar/app_bar_widget.dart';
import 'package:yt_devops/components/card_wrap.dart';
import 'package:yt_devops/components/select_phone_widget.dart';
import 'package:yt_devops/components/yt_button.dart';
import 'package:yt_devops/components/yt_form/utils/form_widget_utils.dart';
import 'package:yt_devops/components/yt_form/value_accessors/poi_value_accessors.dart';
import 'package:yt_devops/components/yt_form/widgets/form_text_field.dart';
import 'package:yt_devops/components/yt_form/widgets/reactive_bruno_date_picker.dart';
import 'package:yt_devops/components/yt_form/widgets/reactive_bruno_input_text.dart';
import 'package:yt_devops/components/yt_form/widgets/reactive_map_pick.dart';
import 'package:yt_devops/components/yt_form/widgets/reactive_text_select.dart';
import 'package:yt_devops/model/amap_poi.dart';

import 'package:yt_devops/model/install_provider_model.dart';
import 'package:yt_devops/model/user_model.dart';
import 'package:yt_devops/pages/common/select_page/select_page_model.dart';
import 'package:yt_devops/pages/site/site_list/site_list_model.dart';

import 'package:yt_devops/resources/resources.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/constants/time_formated.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/toast_utils.dart';
import 'create_repair_task_controller.dart';

class CreateRepairTaskPage extends GetView<CreateRepairTaskController> {
  CreateRepairTaskPage({Key? key}) : super(key: key);

  BrnFormItemConfig theme = BrnFormItemConfig(
      formPadding:
          EdgeInsets.only(left: 6.w, right: 16.w, top: 17.h, bottom: 17.h),
      titlePaddingLg: EdgeInsets.only(left: 10.w),
      disableTextStyle: BrnTextStyle(color: Colour.mainTextColor));

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBarWidget.defaultAppBar(controller.title),
      body: GetBuilder<CreateRepairTaskController>(
          builder: (controller) => ReactiveFormBuilder(
              onWillPop: () async {
                if (FocusScope.of(context).hasFocus) {
                  FocusScope.of(context).unfocus;
                }
                return true;
              },
              form: controller.buildForm,
              builder: (context, form, child) {
                controller.form = form;

                return ListView(
                  children: [
                    CardWrap(
                      padding: EdgeInsets.only(left: 7.w, right: 16.w),
                      child: Column(children: [
                        ReactiveTextSelect<SiteModel, SiteModel>(
                          formControlName: 'site',
                          title: ResKey.siteName.tr,
                          value: (site) => site?.name ?? '',
                          validationMessages: {
                            'required': (error) => ResKey.plsSelectSite.tr
                          },
                          requireStar: true,
                          selectPageProp: SelectPageProp(
                            ResKey.site.tr,
                            getIdByKey: (site) => site.siteId,
                            getNameKey: (site) => site.name ?? '',
                            searchKey: 'siteName',
                            isSearch: true,
                            initSelectValues: form.controls['site']?.value ==
                                    null
                                ? []
                                : [form.controls['site']?.value as SiteModel],
                            service: (params) =>
                                controller.siteServices.getSitesList({
                              'current': params.pageNum,
                              'pageSize': params.pageSize,
                              'status': 2,
                              ...params.extra ?? {}
                            }),
                          ),
                          onChange: () {
                            SiteModel? site =
                                form.controls['site']?.value as SiteModel?;
                            if (site != null) {
                              form.controls['address']?.value =
                                  site.latitude != null &&
                                          site.longitude != null
                                      ? AmapPoi(
                                          latitude: site.latitude!,
                                          longitude: site.longitude!,
                                          formattedAddress: site.address)
                                      : null;
                              controller.update();
                            }
                            form.controls['orgId']?.value = null;
                            form.controls['handlerBy']?.value = null;
                            form.controls['userId']?.value = null;
                          },
                        ),
                        FormTextField(
                          formControlName: 'name',
                          validationMessages: {
                            'required': (error) => ResKey.faultTips.tr
                          },
                          requireStar: true,
                          style: TextStyles.f16,
                          title: ResKey.failureTitle.tr,
                        ),
                        ReactiveBrunoTextInput(
                          formControlName: 'content',
                          title: ResKey.faultDescription.tr,
                          validationMessages: {
                            'required': (error) =>
                                ResKey.faultDescriptionTips.tr
                          },
                          requiredStar: true,
                          showType: ShowType.page,
                          bgColor: Colour.backgroundColor,
                          minHeight: 120.h,
                          minLines: 4,
                        ),
                        ReactiveTextSelect<InstallProviderModel,
                            InstallProviderModel>(
                          formControlName: 'orgId',
                          validationMessages: {
                            'required': (error) => ResKey.installManuTips.tr
                          },
                          title: ResKey.installManu.tr,
                          requireStar: true,
                          value: (InstallProviderModel? v) => v?.orgName ?? '',
                          beforeTap: () {
                            if (form.controls['site']?.value == null) {
                              TotastUtils.tip(context,
                                  title: ResKey.plsSelectASiteFirst.tr);
                              return false;
                            } else {
                              return true;
                            }
                          },
                          onChange: () =>
                              form.controls['handlerBy']?.value = null,
                          selectPageProp: SelectPageProp<InstallProviderModel>(
                            ResKey.installManu.tr,
                            getIdByKey: (model) => model.orgId,
                            getNameKey: (model) => model.orgName ?? '',
                            searchKey: 'orgName',
                            initSelectValues:
                                form.controls['orgId']?.value == null
                                    ? []
                                    : [
                                        form.controls['orgId']?.value
                                            as InstallProviderModel
                                      ],
                            isSearch: true,
                            service: (params) =>
                                controller.services.getInstallProvideList({
                              'current': params.pageNum,
                              'pageSize': params.pageSize,
                              'siteId': form.controls['site']?.value == null
                                  ? null
                                  : (form.controls['site']?.value as SiteModel)
                                      .siteId,
                              ...params.extra ?? {}
                            }, (p0) => false),
                          ),
                        ),
                        ReactiveTextSelect<UserModel, UserModel>(
                          formControlName: 'handlerBy',
                          validationMessages: {
                            'required': (error) => ResKey.maintainerTips.tr
                          },
                          title: ResKey.maintainer.tr,
                          requireStar: true,
                          value: (v) => v?.userName ?? '',
                          beforeTap: () {
                            if (form.controls['orgId']?.value == null) {
                              TotastUtils.tip(context,
                                  title: ResKey.installManuTips.tr);
                              return false;
                            } else {
                              return true;
                            }
                          },
                          selectPageProp: SelectPageProp<UserModel>(
                            ResKey.maintainer.tr,
                            getIdByKey: (model) => model.userId,
                            getNameKey: (model) => model.userName ?? '',
                            searchKey: 'userName',
                            isSearch: true,
                            initSelectValues:
                                form.controls['handlerBy']?.value == null
                                    ? []
                                    : [
                                        form.controls['handlerBy']?.value
                                            as UserModel
                                      ],
                            service: (params) =>
                                controller.services.getInstallerList({
                              'current': params.pageNum,
                              'pageSize': params.pageSize,
                              'orgId': form.controls['orgId']?.value == null
                                  ? null
                                  : (form.controls['orgId']?.value
                                          as InstallProviderModel)
                                      .orgId,
                              ...params.extra ?? {}
                            }, (p0) => false),
                          ),
                        ),
                        ReactiveTextSelect<UserModel, UserModel>(
                          formControlName: 'userId',
                          validationMessages: {
                            'required': (error) => ResKey.selectCustomerName.tr
                          },
                          title: ResKey.customerName.tr,
                          requireStar: true,
                          value: (v) => v?.userName ?? '',
                          selectPageProp: SelectPageProp<UserModel>(
                            ResKey.customerName.tr,
                            getIdByKey: (model) => model.userId,
                            getNameKey: (model) => model.userName ?? '',
                            searchKey: 'userName',
                            isSearch: true,
                            service: (params) =>
                                controller.services.customerList({
                              'current': params.pageNum,
                              'pageSize': params.pageSize,
                              'siteId': form.controls['site']?.value == null
                                  ? null
                                  : (form.controls['site']?.value as SiteModel)
                                      .siteId,
                              ...params.extra ?? {}
                            }, onError: (p0) => false),
                          ),
                          beforeTap: () {
                            if (form.controls['site']?.value == null) {
                              TotastUtils.tip(context,
                                  title: ResKey.plsSelectASiteFirst.tr);
                              return false;
                            } else {
                              return true;
                            }
                          },
                        ),
                        FormTextField(
                          formControlName: 'phone',
                          title: ResKey.contactNumber.tr,
                          validationMessages: {
                            'required': (error) => ResKey.requiredPhoneTip.tr,
                          },
                          keyboardType: TextInputType.phone,
                          requireStar: true,
                          style: TextStyles.f16,
                        ),
                        ReactiveBrunoDatePicker(
                          formControlName: 'timeOfAppointment',
                          pickerMode: BrnDateTimePickerMode.datetime,
                          dateFormat: 'yyyy年,MM月,dd日,HH时:mm分',
                          builder: (context, picker, child) {
                            return ReactiveTextSelect<DateTime, String>(
                              formControlName: 'timeOfAppointment',
                              validationMessages: {
                                'required': (error) =>
                                    ResKey.selectAppointTime.tr
                              },
                              style: TextStyles.f16,
                              requireStar: true,
                              title: ResKey.appointmentTime.tr,
                              onTap: (t) => picker.showPicker(),
                              valueAccessor: DateTimeValueAccessor(
                                  dateTimeFormat: DateFormat(
                                      TimeFormated.dateTimeFromated)),
                            );
                          },
                          minDateTime: DateTime.now(),
                        ),
                        ReactiveTextSelect<MapType, MapType>(
                          formControlName: 'map',
                          requireStar: true,
                          title: ResKey.mapType.tr,
                          value: (v) => v?.label ?? '',
                          onChange: () => controller.update(),
                          selectPageProp: SelectPageProp<MapType>(
                            ResKey.mapType.tr,
                            pickType: PickType.picker,
                            getIdByKey: (model) => model.value,
                            getNameKey: (model) => model.label,
                            isSearch: false,
                            list: MapType.values,
                            initSelectValues:
                                form.controls['map']?.value != null
                                    ? [form.controls['map']!.value as MapType]
                                    : [],
                          ),
                        ),
                        ReactiveMapPicker(
                            formControlName: 'address',
                            mapType: form.controls['map']?.value as MapType,
                            builder: (context, picker, child) {
                              Widget suffix = Padding(
                                padding: const EdgeInsets.only(top: 14),
                                child: Image.asset(ImageAssets.iconDingwei),
                              );

                              if (picker.value == null) {
                                suffix = FormWidgetUtils.getRightArrowIcon();
                              }

                              return ReactiveTextSelect<AmapPoi, String>(
                                onTap: (_) {
                                  picker.showPicker();
                                },
                                valueAccessor: PoiValueAccessor(),
                                formControlName: 'address',
                                requireStar: true,
                                title: ResKey.customerAddress.tr,
                                maxLines: ((form.controls['address'])?.value
                                                as AmapPoi?)
                                            ?.formattedAddress
                                            ?.isNotEmpty ==
                                        true
                                    ? 2
                                    : 1,
                                style: TextStyles.f14,
                                decoration: InputDecoration(
                                  suffixIcon: suffix,
                                ),
                              );
                            })
                      ]),
                    ),
                    CardWrap(
                      padding: EdgeInsets.only(left: 7.w, right: 16.w),
                      child: ReactiveBrunoTextInput(
                        formControlName: 'remark',
                        title: ResKey.siteBaseInfoRemark.tr,
                        autoFocus: false,
                        padding: EdgeInsets.only(left: 12.w),
                      ),
                    ),
                    ReactiveFormConsumer(
                      builder: (context, formGroup, child) => CardWrap(
                        child: SelectPhotoWidget(
                            backgroundColor: Colors.transparent,
                            form.controls['descPicUrl']!.value as List<String>,
                            true,
                            3,
                            decString: ResKey.siteBaseInfoLimitPictures3.tr,
                            titleString: ResKey.imageAttachment.tr,
                            (List<String> list) {
                          controller.update();
                        }),
                      ),
                    ),
                    ReactiveFormConsumer(
                      builder: (context, form, child) => SafeArea(
                        child: CardWrap(
                          margin: const EdgeInsets.only(top: 10),
                          padding: EdgeInsets.symmetric(
                              horizontal: 16.w, vertical: 16.h),
                          child: YtButton(
                            enabled: form.valid,
                            text: ResKey.submit.tr,
                            onPress: () {
                              controller.commit(form);
                            },
                          ),
                        ),
                      ),
                    ),
                  ],
                );
              })),
    );
  }

  Widget borderWidget(Widget child) {
    return Container(
      decoration: const BoxDecoration(
        border: Border(
          bottom: BorderSide(
            color: Colour.dividerColor,
          ),
        ),
      ),
      child: child,
    );
  }
}
